<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :title="isLogin ? '登录' : '注册'"
    width="450px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    class="auth-modal"
    :append-to-body="true"
    @close="handleClose"
  >
    <!-- 头部 -->
    <div class="auth-header">
      <div class="logo-section">
        <div class="logo-icon">🎯</div>
        <h2 class="logo-text">Trainer</h2>
      </div>
      <p class="auth-subtitle">
        {{ isLogin ? '登录您的学习账户，享受完整的平台功能' : '创建您的学习账户，开始您的学习之旅' }}
      </p>
    </div>

    <!-- 登录表单 -->
    <el-form 
      v-if="isLogin"
      :model="loginForm" 
      :rules="loginRules" 
      ref="loginFormRef" 
      class="auth-form"
      @submit.native.prevent="handleLogin"
    >
      <div class="form-group">
        <label class="form-label">用户名</label>
        <el-input 
          v-model="loginForm.username" 
          placeholder="请输入用户名"
          class="form-input"
          prefix-icon="el-icon-user"
        ></el-input>
      </div>

      <div class="form-group">
        <label class="form-label">密码</label>
        <el-input 
          v-model="loginForm.password" 
          type="password" 
          placeholder="请输入密码"
          class="form-input"
          prefix-icon="el-icon-lock"
          show-password
        ></el-input>
      </div>

      <div class="form-options">
        <a href="#" class="forgot-password">忘记密码？</a>
      </div>

      <button 
        type="submit" 
        class="auth-btn primary-btn"
        :disabled="loginLoading"
      >
        <span v-if="loginLoading" class="loading-icon">⏳</span>
        <span v-else class="btn-icon">🔐</span>
        {{ loginLoading ? '登录中...' : '登录' }}
      </button>
    </el-form>

    <!-- 注册表单 -->
    <el-form 
      v-else
      :model="registerForm" 
      :rules="registerRules" 
      ref="registerFormRef" 
      class="auth-form"
      @submit.native.prevent="handleRegister"
    >
      <div class="form-group">
        <label class="form-label">用户名</label>
        <el-input 
          v-model="registerForm.username" 
          placeholder="请输入用户名"
          class="form-input"
          prefix-icon="el-icon-user"
        ></el-input>
      </div>

      <div class="form-group">
        <label class="form-label">密码</label>
        <el-input 
          v-model="registerForm.password" 
          type="password" 
          placeholder="请输入密码"
          class="form-input"
          prefix-icon="el-icon-lock"
          show-password
        ></el-input>
      </div>

      <div class="form-group">
        <label class="form-label">确认密码</label>
        <el-input 
          v-model="registerForm.confirmPassword" 
          type="password" 
          placeholder="请再次输入密码"
          class="form-input"
          prefix-icon="el-icon-lock"
          show-password
        ></el-input>
      </div>

      <button 
        type="submit" 
        class="auth-btn primary-btn"
        :disabled="registerLoading"
      >
        <span v-if="registerLoading" class="loading-icon">⏳</span>
        <span v-else class="btn-icon">📝</span>
        {{ registerLoading ? '注册中...' : '注册' }}
      </button>
    </el-form>

    <!-- 切换按钮 -->
    <div class="auth-switch">
      <p class="switch-text">
        {{ isLogin ? '还没有账户？' : '已有账户？' }}
        <a href="#" class="switch-link" @click="toggleMode">
          {{ isLogin ? '立即注册' : '立即登录' }}
        </a>
      </p>
    </div>
  </el-dialog>
</template>

<script>
import { login, register } from "@/api/user";
import { getUserFromToken } from "@/utils/jwt";

export default {
  name: 'AuthModal',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    defaultMode: {
      type: String,
      default: 'login', // 'login' 或 'register'
      validator: value => ['login', 'register'].includes(value)
    }
  },
  data() {
    // 密码确认验证
    const validateConfirmPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.registerForm.password) {
        callback(new Error('两次输入密码不一致'));
      } else {
        callback();
      }
    };
    
    return {
      isLogin: this.defaultMode === 'login',
      loginLoading: false,
      registerLoading: false,
      
      // 登录表单
      loginForm: {
        username: "",
        password: ""
      },
      loginRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 20, message: "用户名长度在 3 到 20 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, message: "密码长度不能少于 6 个字符", trigger: "blur" }
        ]
      },
      
      // 注册表单
      registerForm: {
        username: "",
        password: "",
        confirmPassword: ""
      },
      registerRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于 6 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: validateConfirmPassword, trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible
      },
      set(value) {
        this.$emit('update:visible', value)
      }
    }
  },
  methods: {
    toggleMode() {
      this.isLogin = !this.isLogin;
      this.clearForms();
    },
    
    clearForms() {
      this.loginForm = { username: "", password: "" };
      this.registerForm = { username: "", password: "", confirmPassword: "" };
      this.$nextTick(() => {
        if (this.$refs.loginFormRef) {
          this.$refs.loginFormRef.clearValidate();
        }
        if (this.$refs.registerFormRef) {
          this.$refs.registerFormRef.clearValidate();
        }
      });
    },
    
    async handleLogin() {
      this.$refs.loginFormRef.validate(async valid => {
        if (!valid) return;
        
        this.loginLoading = true;
        try {
          const res = await login(this.loginForm.username, this.loginForm.password);
          // 处理JWT token响应
          if (res && res.code === 200 && res.data) {
            const token = res.data.token;
            // 从token中解析用户信息
            const tokenUserInfo = getUserFromToken(token);
            console.log(tokenUserInfo);
            
            // 获取完整的用户信息，包括头像
            let fullUserInfo = {
              userId: res.data.id,
              username: tokenUserInfo ? tokenUserInfo.username : this.loginForm.username,
              token: token 
            };
            
            // 尝试获取用户详细信息（包括头像）
            try {
              const { getUser } = await import('@/api/user.js');
              const userDetailRes = await getUser(res.data.id);
              if (userDetailRes && userDetailRes.data) {
                fullUserInfo = {
                  ...fullUserInfo,
                  ...userDetailRes.data,
                  userId: res.data.id,
                  token: token
                };
              }
            } catch (detailError) {
              console.warn('获取用户详细信息失败，使用基本信息:', detailError);
            }
            
            this.$message.success("登录成功！");
            
            // 存储token和用户信息
            localStorage.setItem("token", token);
            localStorage.setItem("user", JSON.stringify(fullUserInfo));
            
            this.$store.commit('setUser', fullUserInfo);
            this.$emit('login-success', fullUserInfo);
            this.handleClose();
          } else {
            this.$message.error(res.message || "用户名或密码错误");
          }
        } catch (e) {
          console.error('登录错误:', e);
          if (e.response && e.response.data && e.response.data.message) {
            this.$message.error(e.response.data.message);
          } else {
            this.$message.error("登录失败，请检查网络连接后重试");
          }
        } finally {
          this.loginLoading = false;
        }
      });
    },
    
    async handleRegister() {
      this.$refs.registerFormRef.validate(async valid => {
        if (!valid) return;
        
        this.registerLoading = true;
        try {
          const res = await register({
            username: this.registerForm.username,
            password: this.registerForm.password
          });
          
          if (res && res.code === 200) {
            this.$message.success(res.data || res.message || '注册成功');
            this.isLogin = true;
            this.clearForms();
          } else {
            this.$message.error((res && res.message) || '注册失败，请稍后重试');
          }
        } catch (e) {
          if (e && e.response && e.response.data && e.response.data.message) {
            this.$message.error(e.response.data.message);
          } else {
            this.$message.error('注册失败，请稍后重试');
          }
        } finally {
          this.registerLoading = false;
        }
      });
    },
    
    handleClose() {
      this.clearForms();
      this.dialogVisible = false;
      this.$emit('close');
    },
    
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.isLogin = this.defaultMode === 'login';
        this.clearForms();
      }
    }
  },
};
</script>

<style scoped>
.auth-modal :deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
  z-index: 9999 !important;
}

.auth-modal :deep(.el-dialog__wrapper) {
  z-index: 9999 !important;
}

.auth-modal :deep(.el-dialog__header) {
  padding: 0;
  border-bottom: none;
}

.auth-modal :deep(.el-dialog__title) {
  display: none;
}

.auth-modal :deep(.el-dialog__headerbtn) {
  top: 20px;
  right: 20px;
  z-index: 10;
}

.auth-modal :deep(.el-dialog__body) {
  padding: 30px;
}

/* 头部样式 */
.auth-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo-section {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  margin-bottom: 15px;
}

.logo-icon {
  font-size: 2rem;
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
}

.logo-text {
  font-size: 1.8rem;
  font-weight: 700;
  background: linear-gradient(135deg, #1e3a8a 0%, #3b82f6 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin: 0;
}

.auth-subtitle {
  color: #7f8c8d;
  font-size: 0.9rem;
  margin: 0 0 15px 0;
  font-weight: 400;
}


/* 表单样式 */
.auth-form {
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 18px;
  text-align: left;
}

.form-label {
  display: block;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 6px;
  font-size: 0.9rem;
}

.form-input {
  width: 100%;
}

.form-input :deep(.el-input__inner) {
  border: 2px solid #e9ecef;
  border-radius: 10px;
  padding: 10px 14px 10px 45px;
  font-size: 0.95rem;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.9);
}

.form-input :deep(.el-input__inner):focus {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
  outline: none;
}

.form-input :deep(.el-input__prefix) {
  color: #7f8c8d;
  font-size: 1rem;
  left: 16px;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  z-index: 1;
}

/* 表单选项 */
.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}


.forgot-password {
  color: #3b82f6;
  text-decoration: none;
  font-size: 0.85rem;
  font-weight: 500;
  transition: color 0.3s ease;
}

.forgot-password:hover {
  color: #1e3a8a;
  text-decoration: underline;
}

/* 按钮样式 */
.auth-btn {
  width: 100%;
  padding: 12px;
  font-size: 1rem;
  font-weight: 600;
  border-radius: 10px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  border: none;
  cursor: pointer;
  background: linear-gradient(135deg, #1e3a8a 0%, #3b82f6 100%);
  color: white;
}

.auth-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(30, 58, 138, 0.3);
}

.auth-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

.loading-icon {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 切换按钮 */
.auth-switch {
  text-align: center;
  margin-bottom: 20px;
}

.switch-text {
  color: #7f8c8d;
  font-size: 0.9rem;
  margin: 0;
}

.switch-link {
  color: #3b82f6;
  text-decoration: none;
  font-weight: 600;
  transition: color 0.3s ease;
}

.switch-link:hover {
  color: #1e3a8a;
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .auth-modal :deep(.el-dialog) {
    width: 90% !important;
    margin: 5vh auto;
  }
  
  .auth-modal :deep(.el-dialog__body) {
    padding: 20px;
  }
  
  .logo-icon {
    font-size: 1.8rem;
  }
  
  .logo-text {
    font-size: 1.6rem;
  }
  
  .form-input :deep(.el-input__inner) {
    padding: 8px 12px 8px 40px;
    font-size: 0.9rem;
  }
}
</style>
